package initialize

import (
	protog "awesomeProject/goods-web/proto" // 也就是如果是在单个主机部署这单个服务，那么就直接awesomeProject/order-web/proto即可
	"awesomeProject/order-web/global"
	"awesomeProject/order-web/proto"
	"awesomeProject/order-web/utils/otgrpc"
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

// InitSrvConn 通过Consul来获取后端子服务的客户端
func InitSrvConn() {

	ConsulInfo := global.ServerConfig.ConsulInfo
	// 维护负载均衡器
	goodsParam := fmt.Sprintf("consul://%s:%d/%s?wait=%s&tag=%s",
		ConsulInfo.Host, ConsulInfo.Port, global.ServerConfig.GoodSrvInfo.Name, "14s", "goods")

	// 实现负载均衡  --- 取出一个链接
	connGoods, err := grpc.Dial(goodsParam, grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()))) // 实现RR轮转负载均衡

	if err != nil {
		zap.S().Fatal("通过Consul负载均衡获得连接失败：", zap.Error(err))
		return
	}
	global.GoodsSrvClient = protog.NewGoodsClient(connGoods)

	// 获取GoodClient
	orderParam := fmt.Sprintf("consul://%s:%d/%s?wait=%s&tag=%s",
		ConsulInfo.Host, ConsulInfo.Port, global.ServerConfig.OrderSrvInfo.Name, "14s", "order")

	// 实现负载均衡  --- 取出一个链接
	connOrder, err := grpc.Dial(orderParam, grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()))) // 实现RR轮转负载均衡

	if err != nil {
		zap.S().Fatal("通过Consul负载均衡获得连接失败：", zap.Error(err))
		return
	}
	global.OrderSrvClient = proto.NewOrderClient(connOrder)

	// 维护负载均衡器
	inventoryParam := fmt.Sprintf("consul://%s:%d/%s?wait=%s&tag=%s",
		ConsulInfo.Host, ConsulInfo.Port, global.ServerConfig.InventorySrvInfo.Name, "14s", "inventory")

	// 实现负载均衡  --- 取出一个链接
	connInventory, err := grpc.Dial(inventoryParam, grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()))) // 实现RR轮转负载均衡

	if err != nil {
		zap.S().Fatal("通过Consul负载均衡获得连接失败：", zap.Error(err))
		return
	}
	global.InventorySrvClient = proto.NewInventoryClient(connInventory)
}
